import axios from 'axios'
import store from '@/store'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const {statusText, status, request: {responseURL}} = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig() {
    const token = '123'
    return {
      baseURL: this.baseUrl,
      headers: {
        Authorization: `Bearer ${token}`,
        // 'Content-Type': 'application/json'
      }
    }
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      // config.data = JSON.stringify(config.data)
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {data, status} = res
      return {data, status}
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {responseURL: config.url}
        }
      } else {
        switch (errorInfo.status) {
          case 400:
            console.warn('错误请求')
            break
          case 401:
            console.warn('未授权，请重新登录')
            break
          case 403:
            console.warn('拒绝访问')
            break
          case 404:
            console.warn('请求错误,未找到该资源')
            break
          case 405:
            console.warn('请求方法未允许')
            break
          case 408:
            console.warn('请求超时')
            break
          case 500:
            console.warn('服务器端出错')
            break
          case 501:
            console.warn('网络未实现')
            break
          case 502:
            console.warn('网络错误')
            break
          case 503:
            console.warn('服务不可用')
            break
          case 504:
            console.warn('网络超时')
            break
          case 505:
            console.warn('http版本不支持该请求')
            break
          default:
            console.warn(`连接错误${errorInfo.status}`)
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
